package com.xjh.mange.controller;

import cn.hutool.core.collection.CollUtil;
import com.xjh.mange.model.Money;
import com.xjh.mange.service.MoneyService;
import com.xjh.mange.vo.ResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 资产
 *
 * @auther xjh
 * @create 2021/2/20
 **/
@Controller
@RequestMapping("/money")
@Slf4j
public class MoneyController {
    @Autowired
    private MoneyService moneyService;

    /**
     * @param money
     * @return com.xjh.mange.Vo.ResponseVO
     * @desc 资产添加或更新
     * @author xjh
     * @date 2021/3/29 20:31
     */
    @PostMapping("/insertOrUpdate")
    @ResponseBody
    public ResponseVO insertOrUpdate(Money money) {
        if (money.getId() == null) {
            List<Money> list = moneyService.list();
            if (CollUtil.isNotEmpty(list)) {
                Money money1 = list.get(0);
                money1.setMoney(money.getMoney().add(money1.getMoney()));
                money1.setUpdateTime(new Date());
                boolean b = moneyService.updateById(money1);
                return b ? ResponseVO.ok("成功") : ResponseVO.error("失败");
            }
            boolean save = moneyService.save(money);
            return save ? ResponseVO.ok("成功") : ResponseVO.error("失败");
        } else {
            Money byId = moneyService.getById(money.getId());
            byId.setMoney(money.getMoney().add(money.getMoney()));
            byId.setUpdateTime(new Date());
            boolean b = moneyService.updateById(byId);
            return b ? ResponseVO.ok("成功") : ResponseVO.error("失败");
        }
    }


    /**
     * @描述 资产展示
     * @作者 xjh
     * @返回 com.xjh.mange.Vo.ResponseVO
     * @时间 2021/3/29 20:08
     */
    @GetMapping("/show")
    @ResponseBody
    public ResponseVO show() {
        List<Money> list = moneyService.list();
        if (CollUtil.isNotEmpty(list)) {
            Money money = list.get(0);
            return ResponseVO.ok(money);
        } else {
            Money money = new Money();
            money.setMoney(new BigDecimal("0"));
            return ResponseVO.ok(money);
        }
    }
}
